<template>
  <div v-loading="loading">
    <el-divider />
    <template v-if="!detailsFlag">
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="form.taskName" :disabled="form.isHiddenValu" placeholder="请输入" style="width: 220px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="迁移类型" prop="migrationType">
            <el-select v-model="form.migrationType" :disabled="form.isHiddenValu" placeholder="请选择迁移类型" clearable filterable @change="changeMigrationType">
              <el-option
                v-for="item in migrationTypeList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
                :disabled="!item.enabled"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="源数据源" prop="sourceConnPkId">
            <el-select v-model="form.sourceConnPkId" filterable :disabled="form.isHiddenValu" placeholder="请选择" clearable style="width:260px" @change="getDatabaseByDataSource()">
              <el-option
                v-for="item in sourceConnList"
                :key="item.pkId"
                :label="item.sourceName"
                :value="item.pkId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标数据源" prop="targetConnPkId">
            <el-select v-model="form.targetConnPkId" filterable :disabled="form.isHiddenValu" placeholder="请选择" clearable style="width:260px">
              <el-option
                v-for="item in targetConnList"
                :key="item.pkId"
                :label="item.sourceName"
                :value="item.pkId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否重建" prop="transferMethod">
            <el-radio-group v-model="form.transferMethod" :disabled="form.isHiddenValu" @change="isRebuild">
              <el-radio-button label="1">重建</el-radio-button>
              <el-radio-button label="0">不重建</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否需分区" prop="needPartition">
            <el-radio-group v-model="form.needPartition" :disabled="form.isHiddenValu" @change="isRebuild">
              <el-radio-button label="1">是</el-radio-button>
              <el-radio-button label="0">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="导入方式">
            <el-radio-group
              v-model="createTaskType"
              :disabled="form.isHiddenValu"
              style="float: left;margin-right: 40px"
            >
              <el-radio-button style="float: left" label="直连" />
              <el-radio-button label="导入" />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="createTaskType==='直连'" :span="12">
          <el-form-item label="库名" prop="sourceDbName">
            <el-select
              v-model="form.sourceDbName"
              filterable
              :disabled="form.isHiddenValu"
              placeholder="请选择"
              clearable
              style="width:200px"
            >
              <el-option v-for="item in dataDbList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-button :disabled="chooseTableDisable()" type="text" @click="toAddTaskAndList">选择需要迁移的表</el-button>
        </el-col>
        <el-col v-else :span="12">
          <el-form-item label="操作">
            <el-button
              style="float: left"
              size="mini"
              :loading="downloadLoading"
              type="primary"
              icon="el-icon-download"
              @click="templateDownload"
            >
              模板下载
            </el-button>
            <el-upload
              ref="uploadExcel"
              style="display: inline-block;margin-left: 5px"
              :loading="uploadLoading"
              action=""
              multiple
              :auto-upload="false"
              :on-change="handleUploadJobChange"
              :file-list="fileList"
              :show-file-list="false"
            >
              <div>
                <el-button
                  style="float: left;"
                  size="mini"
                  type="primary"
                  icon="el-icon-upload2"
                >
                  文件上传
                </el-button>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
    <el-row style="margin-bottom: 10px">
      <el-col :span="3">
        <el-input
          v-model.trim="query.sourceDbName"
          style="width: 150px;"
          placeholder="请输入源库名"
          clearable
          @keyup.enter.native="crud.toQuery"
        />
      </el-col>
      <el-col :span="3">
        <el-input
          v-model="query.sourceTableName"
          style="width: 150px; margin-right: 10px"
          placeholder="请输入源表名"
          clearable
          @keyup.enter.native="crud.toQuery"
        />
      </el-col>
      <div style="margin-top: 2px">
        <rrOperation :crud="crud" />
        <el-button
          v-if="crud.optShow.del"
          slot="reference"
          class="filter-item"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          style="margin-left: 10px"
          :loading="crud.delAllLoading"
          :disabled="crud.selections.length === 0 || form.isHiddenValu"
          @click="toDelete(crud.selections)"
        >
          删除
        </el-button>
      </div>
    </el-row>
    <el-table
      ref="table"
      :data="crud.data"
      border
      max-height="350"
      @selection-change="crud.selectionChangeHandler"
      @filter-change="crud.handleFilterChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="源库名" prop="sourceDbName" />
      <el-table-column label="源表名" prop="sourceTableName" />
      <el-table-column label="目标库名" prop="targetDbName">
        <template slot-scope="scope">
          <el-input v-if="isDbShow[scope.$index]" v-model="scope.row.targetDbName" />
          <span v-if="!isDbShow[scope.$index]">{{ scope.row.targetDbName }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="!detailsFlag">
        <template slot-scope="scope">
          <el-button
            v-if="!isDbShow[scope.$index]"
            :disabled="form.isHiddenValu"
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleDbEdit(scope.$index)"
          />
          <el-button
            v-if="isDbShow[scope.$index]"
            :disabled="form.isHiddenValu"
            size="mini"
            type="success"
            icon="el-icon-check"
            @click="handleDbCheck(scope)"
          />
        </template>
      </el-table-column>

      <el-table-column label="目标表名" prop="targetTableName">
        <template slot-scope="scope">
          <el-input v-if="isShow[scope.$index]" v-model="scope.row.targetTableName" />
          <span v-if="!isShow[scope.$index]">{{ scope.row.targetTableName }}</span>
        </template>
      </el-table-column>

      <el-table-column v-if="!detailsFlag">
        <template slot-scope="scope">
          <el-button
            v-if="!isShow[scope.$index]"
            :disabled="form.isHiddenValu"
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleEdit(scope.$index)"
          />
          <el-button
            v-if="isShow[scope.$index]"
            :disabled="form.isHiddenValu"
            size="mini"
            type="success"
            icon="el-icon-check"
            @click="handleCheck(scope)"
          />
        </template>
      </el-table-column>
      <el-table-column v-if="form.needPartition === '1'" label="分区字段名" prop="partitionFieldNameList">
        <template slot-scope="scope">
          <template>
            <el-select
              v-model="scope.row.partitionFieldNameList"
              :disabled="form.isHiddenValu"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="默认为DT"
              @change="handleInputPartition(scope)"
            >
              <el-option
                v-for="item in partitionFieldNameList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </template>
      </el-table-column>
      <el-table-column v-if="detailsFlag" label="表迁移状态" prop="status">
        <template slot-scope="scope">
          <el-tag :type="dynamicStatus(scope.row)">{{ scope.row.status === 'SUCCESS' ? '成功' : (scope.row.status === 'UNCREATE' ? '待创建' : '失败') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="toFieldDetail(scope.row)">字段详情</el-button>
          <el-button type="text" size="mini" @click="showCreateSql(scope.row)">语句预览</el-button>
          <el-button v-if="detailsFlag" type="text" size="mini" @click="showRunLogMessage(scope.row)">执行信息</el-button>
          <!-- <el-button v-if="detailsFlag" type="text" size="mini" @click="toHistoryDetail(scope.row)">历史记录</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination />
    <!--字段详情-->
    <el-dialog
      v-if="fieldFlag"
      append-to-body
      :visible.sync="fieldFlag"
      :close-on-click-modal="false"
      title="字段详情"
      width="1400px"
      top="5vh"
    >
      <el-form ref="fieldMaps" :inline="true">
        <table-transfer-field-map
          :is-hidden-valu="form.isHiddenValu"
          :list-pk-id="listPkId"
          :field-maps="fieldMaps"
          :partition-field-name="partitionFieldNameTmp"
          :need-partition="form.needPartition"
          :total="total"
          @fieldMapChange="changeMapChange"
        />
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="fieldClose">取消</el-button>
        <el-button v-if="!form.isHiddenValu" type="primary" @click="fieldEdit">保存</el-button>
      </div>
    </el-dialog>
    <!--语句预览-->
    <el-dialog
      :visible.sync="showCreateSqlFlag"
      append-to-body
      :close-on-click-modal="false"
      title="建表语句"
      width="1400px"
      top="5vh"
    >
      <el-form :inline="true" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="源建表语句" prop="sourceCreateSql">
              <el-input
                v-model="sourceCreateSql"
                type="textarea"
                disabled
                placeholder="请输入"
                :autosize="{ minRows: 15, maxRows: 20}"
                style="width: 620px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标建表语句" prop="TargetCreateSql">
              <el-input
                v-model="targetCreateSql"
                :disabled="form.isHiddenValu"
                type="textarea"
                placeholder="请输入"
                :autosize="{ minRows: 15, maxRows: 20}"
                style="width: 620px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="showCreateSqlClose()">取消</el-button>
        <el-button v-if="!form.isHiddenValu" type="primary" @click="showCreateSqlSubmit()">保存</el-button>
      </div>
    </el-dialog>
    <!--历史记录-->
    <el-dialog
      :visible.sync="historyDetail"
      append-to-body
      :close-on-click-modal="false"
      title="历史记录"
      width="1000px"
      top="5vh"
    >
      <el-table :data="runLog">
        <el-table-column label="库名" prop="databaseName" />
        <el-table-column label="表名" prop="tableName" />
        <el-table-column label="更新人" prop="upUserName" />
        <el-table-column label="更新时间" prop="upTs" />
        <el-table-column label="建表预览">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="toPreviewSql(scope.row)">语句预览</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="toHistoryDetailClose()">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="historyPreviewSql"
      append-to-body
      :close-on-click-modal="false"
      title="历史记录"
      width="700px"
      top="5vh"
    >
      <div style="text-align: center">
        <el-input
          v-model="previewSql"
          type="textarea"
          disabled
          placeholder=""
          :autosize="{ minRows: 15, maxRows: 20}"
          style="width: 620px"
        />
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="historyPreviewSql=false">关闭</el-button>
      </div>
    </el-dialog>
    <!--建表清单选择-->
    <el-dialog
      append-to-body
      :visible.sync="chooseTable"
      :modal-append-to-body="false"
      title="选择要迁移的表"
      width="1000px"
    >
      <el-transfer
        v-if="chooseTable"
        v-model="chooseData"
        style="text-align: left; display: inline-block"
        filterable
        :titles="['待选-迁移表清单', '已选-迁移表清单']"
        :button-texts="['撤销', '添加']"
        :data="dataTableList"
      >
        <span slot-scope="{ option }">
          <el-tooltip
            class="item"
            :content="option.label"
            placement="top"
          >
            <span>{{ option.label }}</span>
          </el-tooltip>
        </span>
      </el-transfer>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="cancelChoose()">取消</el-button>
        <el-button type="primary" @click="submitChoose()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="showRunLogMessageFlag"
      title="表迁移日志"
      width="1200px"
      top="5vh"
    >
      <monaco-editor
        ref="convertMonaco"
        v-model="runLogMessage"
        style="height: 430px"
      />
    </el-dialog>
  </div>
</template>

<script>
import tableTransferTask from '@/api/data/table/tableTransferTask'
import tableTransferList from '@/api/data/table/tableTransferList'
import tableTransferRunLog from '@/api/data/table/tableTransferRunLog'
import tableTransferFieldMapApi from '@/api/data/table/tableTransferFieldMap'
import dataSourceApi from '@/api/metadata/dataSource'
import CRUD, { presenter, header, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'
import TableTransferFieldMap from './table-transfer-field-map.vue'
import { downloadFile } from '@utils'
import { crunDate } from '@utils/data'
import { upload } from '@/api/data'
import MonacoEditor from '@/components/MonacoEditor/monacoEditor'

const defaultCrud = CRUD({
  title: '表迁移清单',
  url: '/api/data/table/list/queryPageListByTaskId',
  crudMethod: { ...tableTransferList }
})
export default {
  name: 'CreateTask',
  // eslint-disable-next-line vue/no-unused-components
  components: { TableTransferFieldMap, rrOperation, pagination, MonacoEditor },
  mixins: [presenter(defaultCrud), header(), crud()],
  props: {
    form: {
      required: true,
      type: Object
    },
    taskPkId: {
      required: true,
      type: String
    },
    detailsFlag: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      binaryData: null,
      fileList: [],
      acceptFileType: '.xls,.xlsx',
      migrationTypeList: [],
      downloadLoading: false,
      fieldFlag: false,
      showCreateSqlFlag: false,
      historyDetail: false,
      sourceConnList: [],
      targetConnList: [],
      dataDbList: [],
      dataTableList: [],
      createTaskType: '直连',
      sourceDbName: '',
      targetDbName: '',
      chooseTable: false,
      chooseData: [],
      originalList: '',
      listPkId: '',
      transferList: [],
      isShow: [],
      isDbShow: [],
      isShowPartition: [],
      showCreateSqlRow: [],
      sourceCreateSql: null,
      targetCreateSql: null,
      runLog: [],
      previewSql: null,
      historyPreviewSql: false,
      fieldMaps: [],
      total: null,
      partitionFields: [
        {
          value: 'DT',
          label: 'DT'
        }
      ],
      partitionFieldNameTmp: [],
      partitionFieldNameList: [],
      initTotal: 0,
      loading: false,
      uploadLoading: false,
      showRunLogMessageFlag: false,
      runLogMessage: ''
    }
  },
  created() {
    this.initData()
  },
  methods: {
    [CRUD.HOOK.beforeRefresh](crud) {
      if (this.taskPkId !== null && this.taskPkId !== '') {
        crud.query.taskPkId = this.taskPkId
      } else {
        crud.query.taskPkId = ''
      }
    },
    // 新增建表任务并获取所选库的所有表信息
    toAddTaskAndList() {
      this.toAddTask()
      this.toAddList()
    },
    // 新增建表任务
    toAddTask() {
      if (this.form.pkId === null || this.form.pkId === '') {
        tableTransferTask.add(this.form).then(rsp => {
          this.form.pkId = rsp
          this.form.validateName = this.form.taskName
        })
      }
    },
    // 获取所选库的所有表信息添加到穿梭框可选列中
    toAddList() {
      this.loading = true
      const param = { pkId: this.form.sourceConnPkId, schema: this.form.sourceDbName }
      this.dataTableList = []
      dataSourceApi.tables(param).then(data => {
        this.loading = false
        data.forEach((array) => {
          this.dataTableList.push({
            label: array,
            key: array
          })
        })
        this.initSelectData()
      }).catch((err) => {
        // 捕获异常并打印错误信息
        this.loading = false
        console.log(err)
      })
    },
    initSelectData() {
      this.chooseData = []
      this.dataTableList.forEach(val => {
        this.crud.data.forEach(item => {
          const dataForm = this.form
          if (dataForm.sourceConnPkId === item.sourceConnPkId &&
            dataForm.sourceDbName === item.sourceDbName && val.key === item.sourceTableName) {
            this.chooseData.push(val.key)
          }
        })
      })
      this.chooseTable = true
    },
    // 取消穿梭框选择
    cancelChoose() {
      this.chooseTable = false
      this.dataTableList = []
      this.chooseData = []
    },
    // 提交穿梭框选择
    submitChoose() {
      this.chooseTable = false
      this.addTransferList()
      this.chooseData = []
      this.dataTableList = []
      this.crud.refresh()
    },
    // 根据穿梭选择框所选的表 添加到建表清单中
    addTransferList() {
      const newChooseData = this.dealChooseData(this.chooseData)
      // console.log("this.chooseData---",this.chooseData)
      this.crud.notify('正在获取字段信息', CRUD.NOTIFICATION_TYPE.SUCCESS)
      newChooseData.forEach((array) => {
        const param = {
          taskPkId: this.taskPkId,
          sourceDbName: this.form.sourceDbName,
          targetDbName: this.form.sourceDbName,
          sourceTableName: array,
          targetTableName: array,
          partitionFieldName: this.form.partitionFieldName === '' ? 'DT' : this.form.partitionFieldName,
          sourceConnPkId: this.form.sourceConnPkId,
          targetConnPkId: this.form.targetConnPkId,
          transferMethod: this.form.transferMethod,
          needPartition: this.form.needPartition,
          status: 'UNCREATE'
        }
        tableTransferList.add(param).then(data => {
          this.form.tableTransferList.push({
            pkId: data,
            sourceDbName: this.form.sourceDbName,
            targetDbName: this.form.sourceDbName,
            sourceTableName: array,
            targetTableName: array,
            partitionFieldName: this.form.partitionFieldName
          })
          this.getFieldMapAndCreateSql(this.form.sourceConnPkId, this.form.targetConnPkId, data)
        })
      })
    },
    dealChooseData(chooseList) {
      const tmpList = []
      this.crud.data.forEach(info => {
        tmpList.push(info.sourceTableName)
      })
      chooseList = chooseList.filter(function(item) {
        return tmpList.indexOf(item) < 0
      })
      return chooseList
    },
    // 获取字段映射信息并生成建表SQL
    async getFieldMapAndCreateSql(sourceConnPkId, targetConnPkId, listPkId) {
      await tableTransferList.getFieldMap(sourceConnPkId, targetConnPkId, listPkId)
      await this.crud.refresh()
      await this.getShowCreateSql(listPkId)
      await this.crud.refresh()
    },
    // 进入字段映射详情信息界面
    toFieldDetail(row) {
      this.partitionFieldNameTmp = row.partitionFieldNameList
      if (row.pkId !== undefined) {
        this.listPkId = row.pkId
        const param = { listPkId: row.pkId }
        tableTransferFieldMapApi.findListByPage(param).then(data => {
          this.fieldMaps = data.content
          this.total = data.total
          this.fieldFlag = true
        })
        this.fieldFlag = true
      } else {
        this.fieldFlag = true
      }
    },
    // 关闭字段映射详情信息界面
    fieldClose() {
      this.fieldFlag = false
    },
    // 编辑字段映射详情操作
    async fieldEdit() {
      let flag = 0
      this.fieldMaps.forEach(fieldInfo => {
        if (fieldInfo.isPartitionField === 'Y' && (fieldInfo.partitionFieldMapping === '' || fieldInfo.partitionFieldMapping === null || fieldInfo.partitionFieldMapping === undefined)) {
          flag++
        }
      })
      if (flag !== 0) {
        this.crud.notify('请选择分区字段映射信息', CRUD.NOTIFICATION_TYPE.SUCCESS)
      } else {
        await this.editFieldInfo()
        this.fieldFlag = false
        await this.reBuildSql(this.fieldMaps[0].listPkId)
      }
    },
    // 更改字段映射信息
    editFieldInfo() {
      this.fieldMaps.forEach((array) => {
        tableTransferFieldMapApi.edit(array)
      })
    },
    // 更改字段映射信息后重新生成SQL语句
    async reBuildSql(listPkId) {
      await tableTransferList.buildSql(listPkId).then(data => {
        this.sourceCreateSql = data.sourceCreateSql
        this.targetCreateSql = data.targetCreateSql
      })
      await this.crud.refresh()
      await this.crud.notify('SQL已重新生成！', CRUD.NOTIFICATION_TYPE.SUCCESS)
    },
    // 进入建表语句预览页面
    showCreateSql(row) {
      this.crud.refresh()
      this.showCreateSqlRow = row
      if (row.targetCreateSql !== undefined && row.targetCreateSql !== null) {
        this.sourceCreateSql = row.sourceCreateSql
        this.targetCreateSql = row.targetCreateSql
        this.showCreateSqlFlag = true
      } else {
        this.crud.notify('SQL语句生成中,请稍后查看！', CRUD.NOTIFICATION_TYPE.WARNING)
      }
    },
    // 生成建表SQL
    getShowCreateSql(listPkId) {
      tableTransferList.buildSql(listPkId).then(data => {
        this.sourceCreateSql = data.sourceCreateSql
        this.targetCreateSql = data.targetCreateSql
      })
    },
    // 关闭建表SQL预览界面
    showCreateSqlClose() {
      this.showCreateSqlFlag = false
    },
    // 保存对建表SQL修改
    showCreateSqlSubmit() {
      const param = {
        pkId: this.showCreateSqlRow.pkId,
        targetDbName: this.showCreateSqlRow.targetDbName,
        targetTableName: this.showCreateSqlRow.targetTableName,
        partitionFieldName: this.showCreateSqlRow.partitionFieldName,
        partitionFieldNameList: this.showCreateSqlRow.partitionFieldNameList,
        targetCreateSql: this.targetCreateSql
      }
      tableTransferList.edit(param)
      this.showCreateSqlFlag = false
      this.crud.refresh()
    },
    showRunLogMessage(row) {
      const param = {
        listPkId: row.pkId
      }
      tableTransferRunLog.findListByPage(param).then((data) => {
        this.runLogMessage = data.content[0].message
      })
      this.showRunLogMessageFlag = true
    },
    // 进入建表历史页面 -- 暂时关闭该页面
    toHistoryDetail(row) {
      const param = {
        listPkId: row.pkId
      }
      tableTransferRunLog.findListByPage(param).then((data) => {
        this.runLog = data.content
      })
      this.historyDetail = true
    },
    // 建表历史界面预览建表SQL
    toPreviewSql(row) {
      this.previewSql = row.createSql
      this.historyPreviewSql = true
    },
    // 关闭建表历史页面
    toHistoryDetailClose() {
      this.historyDetail = false
    },
    // 进入目标表名编辑按钮
    handleEdit(index) {
      this.$set(this.isShow, index, true)
    },
    // 提交对目标表名的修改
    async handleCheck(scope) {
      this.$set(this.isShow, scope.$index, false)
      if (scope.row.partitionFieldNameList.length === 0) {
        scope.row.partitionFieldNameList = ['DT']
      }
      // scope.row.partitionFieldNameList.length === 0 ? scope.row.partitionFieldNameList = ['DT'] : scope.row.partitionFieldNameList
      await tableTransferList.edit(scope.row)
      await tableTransferList.buildSql(scope.row.pkId).then(data => {
        this.sourceCreateSql = data.sourceCreateSql
        this.targetCreateSql = data.targetCreateSql
      })
      this.crud.refresh()
      await this.crud.notify('SQL已重新生成！', CRUD.NOTIFICATION_TYPE.SUCCESS)
    },
    // 进入目标库名编辑按钮
    handleDbEdit(index) {
      this.$set(this.isDbShow, index, true)
    },
    // 提交对目标库名的修改
    async handleDbCheck(scope) {
      this.$set(this.isDbShow, scope.$index, false)
      if (scope.row.partitionFieldNameList.length === 0) {
        scope.row.partitionFieldNameList = ['DT']
      }
      // scope.row.partitionFieldNameList.length === 0 ? scope.row.partitionFieldNameList = ['DT'] : scope.row.partitionFieldNameList
      await tableTransferList.edit(scope.row)
      await tableTransferList.buildSql(scope.row.pkId).then(data => {
        this.sourceCreateSql = data.sourceCreateSql
        this.targetCreateSql = data.targetCreateSql
      })
      this.crud.refresh()
      await this.crud.notify('SQL已重新生成！', CRUD.NOTIFICATION_TYPE.SUCCESS)
    },
    // 输入分区字段操作
    handleInputPartition(scope) {
      const param = {
        ...scope.row,
        partitionFieldNameList: scope.row.partitionFieldNameList.length === 0 ? ['DT'] : scope.row.partitionFieldNameList
      }
      tableTransferList.edit(param)
    },
    // 进入页面后初始化信息
    async initData() {
      // this.crud.resetQuery(false)
      this.initMigrationTypeList()
      if (!this.form.isHiddenValu && !this.form.pkId) {
        this.form.taskName = `表迁移-${crunDate()}`
        const data = await dataSourceApi.findDefaultSource()
        const sourceDefault = data.find(item => item.isDefault === 'ENABLE' && item.sourceAttribute === 'source')
        const targetDefault = data.find(item => item.isDefault === 'ENABLE' && item.sourceAttribute === 'target')
        if (sourceDefault !== undefined && targetDefault !== undefined) {
          const currentMigrationType = sourceDefault.sourceType + '-' + targetDefault.sourceType
          if (this.migrationTypeList.some(item => item.name === currentMigrationType && item.enabled === true)) {
            this.form.migrationType = currentMigrationType
            this.changeMigrationType(currentMigrationType)
            this.form.sourceConnPkId = sourceDefault === undefined ? '' : sourceDefault.pkId
            this.form.targetConnPkId = targetDefault === undefined ? '' : targetDefault.pkId
          }
        }
      } else {
        this.changeMigrationType(this.form.migrationType)
      }
      await this.getDatabaseByDataSource()
    },
    changeMigrationType(val) {
      const sourceTypes = val.split('-')
      this.initSourceConnList(sourceTypes[0])
      this.initTargetConnList(sourceTypes[1])
      this.form.sourceDbName = ''
    },
    // 获取数据源信息
    initSourceConnList(sourceType) {
      const params = { serverType: 'SOURCE', status: 'ENABLE', sourceType: sourceType, size: 10000 }
      dataSourceApi.findListByPage(params).then(res => {
        if (res.total > 0) {
          this.sourceConnList = res.content
        }
      })
    },
    initTargetConnList(targetType) {
      const params = { serverType: 'TARGET', sourceType: targetType, size: 10000 }
      dataSourceApi.findListByPage(params).then(res => {
        if (res.total > 0) {
          this.targetConnList = res.content
        }
      })
    },
    initMigrationTypeList() {
      tableTransferTask.getMigrationTypeInfos().then(res => {
        this.migrationTypeList = res
      })
    },
    // 根据数据源信息获取数据库列表
    getDatabaseByDataSource() {
      this.dataDbList = []
      this.form.sourceDbName = ''
      if (this.form.sourceConnPkId !== '') {
        dataSourceApi.schemas(this.form.sourceConnPkId).then((data) => {
          this.dataDbList = data
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 文件上传操作
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    // 移除所上传文件
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 动态禁用选择要迁移的表按钮
    chooseTableDisable() {
      return this.form.isHiddenValu || this.form.taskName === null || this.form.taskName === '' ||
        this.form.transferMethod === null || this.form.sourceConnPkId === '' || this.form.targetConnPkId === '' ||
        this.form.sourceDbName === ''
    },
    // 动态建表状态背景色
    dynamicStatus(row, type) {
      if (row.status === 'SUCCESS') {
        return 'success'
      } else if (row.status === 'FAIL') {
        return 'danger'
      } else {
        return ''
      }
    },
    async toDelete(datas) {
      let delFlag = 0
      datas.forEach(data => {
        if (data.targetCreateSql === null) {
          delFlag++
        }
      })
      if (delFlag === 0) {
        await this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.delAllLoading = true
          this.crud.doDelete(datas)
        }).catch(() => {
        })
      } else {
        this.crud.notify('请等待建表SQL处理结束后重试！', CRUD.NOTIFICATION_TYPE.WARNING)
      }
      const param = { taskPkId: this.form.pkId }
      await tableTransferList.findListByPage(param).then(data => {
        this.form.tableTransferList = data.content
      })
    },
    async isRebuild(val) {
      const promises = this.crud.data.map(async item => {
        item.transferMethod = this.form.transferMethod
        item.needPartition = this.form.needPartition
        await tableTransferList.edit(item)
        await tableTransferList.buildSql(item.pkId)
      })
      await Promise.all(promises)
      if (this.crud.data.length !== 0) {
        await tableTransferTask.edit({
          pkId: this.form.pkId,
          transferMethod: this.form.transferMethod,
          needPartition: this.form.needPartition
        })
        await this.crud.refresh()
        this.crud.notify('SQL已重新生成！', CRUD.NOTIFICATION_TYPE.SUCCESS)
      }
    },
    templateDownload() {
      const pkIds = this.crud.selections.map(item => {
        return item.pkId
      })
      this.downloadLoading = true
      tableTransferList.download(pkIds)
        .then(result => {
          downloadFile(result, '表迁移清单', 'xlsx')
          this.downloadLoading = false
        }).catch(() => {
          this.downloadLoading = false
        })
    },
    handleUploadJobChange(file, fileList) {
      if (this.form.sourceConnPkId === undefined || this.form.sourceConnPkId === '' || this.form.sourceConnPkId === null) {
        this.crud.notify('请选择源数据源类型!', CRUD.NOTIFICATION_TYPE.ERROR)
        this.fileList = []
        return false
      } else if (this.form.targetConnPkId === undefined || this.form.targetConnPkId === '' || this.form.targetConnPkId === null) {
        this.crud.notify('请选择目标数据源类型!', CRUD.NOTIFICATION_TYPE.ERROR)
        this.fileList = []
        return false
      }
      const fileName = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (fileName !== 'xlsx' && fileName !== 'xls') {
        this.crud.notify('文件类型应为excel文件!', CRUD.NOTIFICATION_TYPE.ERROR)
        this.fileList = []
        return false
      }
      this.fileList = fileList
      if (this.fileList.length > 0) {
        this.uploadLoading = true
        // const formData = new FormData()
        const formData = new FormData()
        this.fileList.forEach((element, i) => {
          formData.append('file', element.raw)
        })
        formData.append('tableTransferListExcelDto', JSON.stringify(this.form))
        this.crud.notify('表迁移任务解析中...', CRUD.NOTIFICATION_TYPE.WARNING)
        upload('api/data/table/list/importTableTransfer', formData).then(res => {
          this.uploadLoading = false
          this.taskPkId = res.taskId
          this.form.pkId = res.taskId
          if (res.status) {
            this.crud.notify('导入成功!', CRUD.NOTIFICATION_TYPE.SUCCESS)
            // this.getFieldMapAndCreateSql(this.form.sourceConnPkId, this.form.targetConnPkId, this.pkIds)
            this.$refs.uploadExcel.clearFiles()
            this.crud.refresh()
          } else {
            this.taskPkId = ''
            this.form.pkId = ''
            this.crud.notify('导入失败!', CRUD.NOTIFICATION_TYPE.ERROR)
            this.crud.refresh()
          }
        })
      } else {
        this.$notify.error({
          title: '错误',
          message: '请选择导入的文件!'
        })
      }
    },
    changeMapChange(val) {
      this.fieldMaps = val
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.el-divider--horizontal {
  margin: 24px 0;
};
.el-col-3{
  margin-right: 10px
}
::v-deep .el-transfer-panel{
  width: 350px;
  height: 500px;
}
::v-deep .el-transfer-panel__list{
  height: 400px;
}
.upload-demo {
  display: inline-block;
  margin-left: 10px;
}
</style>
